<template>
  <CommonLayout
    pageTitle="卖家交易管理"
    sidebarTitle="订单筛选"
    :loading="loading"
    :isEmpty="orders.length === 0 && !loading"
    emptyText="暂无订单数据"
  >
    <!-- 侧边栏筛选区 -->
    <template #sidebar>
      <form class="filter-form" @submit.prevent="handleFilter">
        <div class="filter-item">
          <label>订单编号</label>
          <input
            v-model="filterForm.orderId"
            placeholder="输入订单编号"
            class="filter-input"
          />
        </div>

        <div class="filter-item">
          <label>商品名称</label>
          <input
            v-model="filterForm.productName"
            placeholder="输入商品名称"
            class="filter-input"
          />
        </div>

        <div class="filter-item">
          <label>订单状态</label>
          <select v-model="filterForm.status" class="filter-select">
            <option value="">全部状态</option>
            <option value="0">待付款</option>
            <option value="1">已付款</option>
            <option value="2">已发货</option>
            <option value="3">已收货</option>
            <option value="4">已完成</option>
            <option value="5">已取消</option>
          </select>
        </div>

        <div class="filter-item">
          <label>时间筛选</label>
          <div class="date-range">
            <input
              v-model="filterForm.startDate"
              type="date"
              class="date-input"
            />
            <span class="date-separator">至</span>
            <input
              v-model="filterForm.endDate"
              type="date"
              class="date-input"
            />
          </div>
        </div>

        <button type="submit" class="filter-btn">应用筛选</button>
        <button
          type="button"
          class="reset-btn"
          @click="resetFilter"
        >
          重置筛选
        </button>
      </form>
    </template>

    <!-- 主内容区 -->
    <template #content>
      <div class="order-table-container">
        <table class="order-table">
          <thead>
            <tr>
              <th>订单编号</th>
              <th>商品名称</th>
              <th>买家</th>
              <th>订单金额</th>
              <th>创建时间</th>
              <th>订单状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in orders" :key="order.order_id" class="order-row">
              <td>{{ order.order_id }}</td>
              <td>{{ order.product_name }}</td>
              <td>{{ order.buyer_name }}</td>
              <td>￥{{ order.total_amount.toFixed(2) }}</td>
              <td>{{ formatDate(order.created_at) }}</td>
              <td>
                <span :class="['status-tag', getStatusClass(order.status)]">
                  {{ getStatusText(order.status) }}
                </span>
              </td>
              <td class="action-buttons">
                <!-- 主要操作按钮 -->
                <button
                  :class="['btn-common', getMainButtonClass(order.status)]"
                  :disabled="isMainButtonDisabled(order.status)"
                  @click="handleMainAction(order.order_id)"
                >
                  {{ getMainButtonText(order.status) }}
                </button>
                <!-- 取消订单按钮 -->
                <button
                  class="btn-common btn-cancel"
                  :disabled="!isCancelButtonEnabled(order.status)"
                  @click="handleCancelOrder(order.order_id)"
                >
                  取消订单
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <div class="pagination-info">
            共 {{ totalPages }} 页，当前第 {{ currentPage }} 页，每页 {{ pageSize }} 条
          </div>
          <div class="pagination-buttons">
            <button @click="prevPage" :disabled="currentPage === 1" class="pagination-btn">上一页</button>
            <button
              v-for="page in pageRange"
              :key="page"
              @click="goToPage(page)"
              :class="{ 'pagination-btn': true, 'active': page === currentPage }"
            >
              {{ page }}
            </button>
            <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">下一页</button>
          </div>
        </div>
      </div>
    </template>
  </CommonLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import axios from 'axios';
import moment from 'moment';
import CommonLayout from '../components/CommonLayout.vue';
import { formatDate } from '../utils/date-utils.ts';
import { ElMessage } from 'element-plus';

// 定义订单接口类型
interface Order {
  order_id: string;
  product_id: number;
  product_name: string;
  product_price: number;
  total_amount: number;
  buyer_id: number;
  buyer_name: string;
  seller_id: number;
  status: number;
  created_at: string;
  updated_at: string;
}

// 分页相关状态
const currentPage = ref(1);
const totalPages = ref(1);
const pageSize = ref(10);

// 状态管理
const orders = ref<Order[]>([]);
const loading = ref<boolean>(false);

// 筛选表单数据
const filterForm = reactive<{
  orderId: string;
  productName: string;
  status: string;
  startDate: string;
  endDate: string;
}>({
  orderId: '',
  productName: '',
  status: '',
  startDate: '',
  endDate: ''
});

/**
 * 获取页码范围，用于显示分页按钮
 * @returns 页码数组
 */
const pageRange = computed(() => {
  const range = [];
  const maxVisiblePages = 5;
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;

  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

/**
 * 跳转到上一页
 */
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchOrders();
  }
};

/**
 * 跳转到下一页
 */
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchOrders();
  }
};

/**
 * 跳转到指定页码
 * @param page 目标页码
 */
const goToPage = (page: number) => {
  if (page !== currentPage.value && page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
    fetchOrders();
  }
};

/**
 * 应用筛选条件
 */
const handleFilter = () => {
  currentPage.value = 1;
  fetchOrders();
};

/**
 * 重置筛选条件
 */
const resetFilter = () => {
  filterForm.orderId = '';
  filterForm.productName = '';
  filterForm.status = '';
  filterForm.startDate = '';
  filterForm.endDate = '';
  currentPage.value = 1;
  fetchOrders();
};

/**
 * 获取订单列表数据
 */
const fetchOrders = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    // 构建筛选参数
    const params = {
      orderId: filterForm.orderId || undefined,
      productName: filterForm.productName || undefined,
      status: filterForm.status || undefined,
      startDate: filterForm.startDate || undefined,
      endDate: filterForm.endDate || undefined,
      page: currentPage.value,
      pageSize: pageSize.value
    };

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [订单列表] 请求参数:`, params);

    const response = await axios.get('/api/seller/orders', {
      headers: { Authorization: `Bearer ${token}` },
      params
    });

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [订单列表] 响应结果:`, response.data);

    // 更新分页信息
    totalPages.value = response.data.pagination?.totalPages || 1;
    orders.value = response.data.orders.map((order: any) => ({
      ...order,
      total_amount: Number(order.total_amount)
    })) || [];
  } catch (error: any) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [订单列表] 获取失败:`, error);
    ElMessage.error(`获取订单列表失败: ${error.message || '未知错误'}`);
    orders.value = [];
    totalPages.value = 1;
  } finally {
    loading.value = false;
  }
};

/**
 * 根据订单状态获取状态文本
 * @param status 订单状态
 * @returns 状态文本
 */
const getStatusText = (status: number): string => {
  switch (status) {
    case 0: return '待付款';
    case 1: return '已付款';
    case 2: return '已发货';
    case 3: return '已收货';
    case 4: return '已完成';
    case 5: return '已取消';
    default: return '未知状态';
  }
};

/**
 * 根据订单状态获取状态标签类名
 * @param status 订单状态
 * @returns CSS类名
 */
const getStatusClass = (status: number): string => {
  switch (status) {
    case 0: return 'status-pending';
    case 1: return 'status-paid';
    case 2: return 'status-shipped';
    case 3: return 'status-delivered';
    case 4: return 'status-completed';
    case 5: return 'status-canceled';
    default: return 'status-unknown';
  }
};

/**
 * 获取主要操作按钮文本
 * @param status 订单状态
 * @returns 按钮文本
 */
const getMainButtonText = (status: number): string => {
  switch (status) {
    case 0: return '待付款';
    case 1: return '已发货';
    case 2: return '已发货';
    case 3: return '已发货';
    case 4: return '已完成';
    case 5: return '已取消';
    default: return '已完成';
  }
};

/**
 * 获取主要操作按钮类名
 * @param status 订单状态
 * @returns CSS类名
 */
const getMainButtonClass = (status: number): string => {
  if (isMainButtonDisabled(status)) {
    return 'btn-disabled';
  }
  switch (status) {
    case 0: return 'btn-payment';
    case 1: return 'btn-ship';
    case 3: return 'btn-complete';
    default: return 'btn-disabled';
  }
};

/**
 * 判断主要操作按钮是否禁用
 * @param status 订单状态
 * @returns 是否禁用
 */
const isMainButtonDisabled = (status: number): boolean => {
  // 状态0（待付款）、1（已付款）、3（已收货）时启用
  // 其他状态禁用
  return ![0, 1, 3].includes(status);
};

/**
 * 判断取消订单按钮是否启用
 * @param status 订单状态
 * @returns 是否启用
 */
const isCancelButtonEnabled = (status: number): boolean => {
  // 订单状态为0（未付款）、1（已付款）、2（已发货）、3（已收货）时启用
  return [0, 1, 2, 3].includes(status);
};

/**
 * 处理主要操作按钮点击事件
 * @param orderId 订单ID
 */
const handleMainAction = async (orderId: string) => {
  try {
    const token = localStorage.getItem('token');
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [订单操作] 执行卖家主要操作, 订单ID:`, orderId);

    const response = await axios.put(
      `/api/seller/orders/${orderId}/status`,
      {},
      {
        headers: { Authorization: `Bearer ${token}` }
      }
    );

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [订单操作] 主要操作成功, 响应:`, response.data);
    ElMessage.success('订单状态更新成功');
    fetchOrders(); // 刷新订单列表
  } catch (error: any) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [订单操作] 主要操作失败:`, error);
    ElMessage.error(`订单操作失败: ${error.message || '未知错误'}`);
  }
};

/**
 * 处理取消订单按钮点击事件
 * @param orderId 订单ID
 */
const handleCancelOrder = async (orderId: string) => {
  try {
    const token = localStorage.getItem('token');
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [订单操作] 取消订单, 订单ID:`, orderId);

    const response = await axios.put(
      `/api/seller/orders/${orderId}/cancel`,
      {},
      {
        headers: { Authorization: `Bearer ${token}` }
      }
    );

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [订单操作] 取消订单成功, 响应:`, response.data);
    ElMessage.success('订单已取消');
    fetchOrders(); // 刷新订单列表
  } catch (error: any) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [订单操作] 取消订单失败:`, error);
    ElMessage.error(`取消订单失败: ${error.message || '未知错误'}`);
  }
};

// 页面加载时获取订单列表
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-table-container {
  overflow-x: auto;
}

.order-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

.order-table th,
.order-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #e2e8f0;
}

.order-table th {
  background-color: #f8fafc;
  font-weight: 600;
  color: #1e293b;
}

.order-row:hover {
  background-color: #f8fafc;
}

.status-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: #fef3c7;
  color: #92400e;
}

.status-paid {
  background-color: #dbeafe;
  color: #1e40af;
}

.status-shipped {
  background-color: #d1fae5;
  color: #065f46;
}

.status-delivered {
  background-color: #e0e7ff;
  color: #4338ca;
}

.status-completed {
  background-color: #d1d5db;
  color: #4b5563;
}

.status-canceled {
  background-color: #fee2e2;
  color: #b91c1c;
}

.status-unknown {
  background-color: #f3f4f6;
  color: #6b7280;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-common {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: all 0.2s;
}

.btn-payment {
  background-color: #3b82f6;
  color: white;
}

.btn-ship {
  background-color: #10b981;
  color: white;
}

.btn-complete {
  background-color: #8b5cf6;
  color: white;
}

.btn-cancel {
  background-color: #ef4444;
  color: white;
}

.btn-cancel:disabled {
  background-color: #d1d5db;
  color: #9ca3af;
  cursor: not-allowed;
}

.btn-disabled {
  background-color: #d1d5db;
  color: #9ca3af;
  cursor: not-allowed;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e2e8f0;
}

.pagination-info {
  color: #64748b;
  font-size: 14px;
}

.pagination-buttons {
  display: flex;
  gap: 8px;
}

.pagination-btn {
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
  background-color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.pagination-btn:hover:not(.active):not(:disabled) {
  background-color: #f8fafc;
}

.pagination-btn.active {
  background-color: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.pagination-btn:disabled {
  color: #9ca3af;
  cursor: not-allowed;
}

.filter-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-item label {
  font-weight: 500;
  color: #1e293b;
}

.filter-input,
.filter-select {
  width: 100%;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
  font-size: 14px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-input {
  flex: 1;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
  font-size: 14px;
}

.date-separator {
  color: #64748b;
}

.filter-btn {
  background-color: #3b82f6;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.reset-btn {
  background-color: #f1f5f9;
  color: #64748b;
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }
}
</style>